package com.example.myapplication2;

import android.widget.Toast;

import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Api {

    private static final String API_URL = "https://api.moonshot.cn/v1/chat/completions";
    private static final String MOONSHOT_API_KEY = "sk-iDEJFVLoSN8ujF2Xm5raEHPGWdbJRx2PZpkrSAC5HexhxrSb"; // 替换为你的API密钥

    public String sendMessage(final MainActivity activity,String input) {
        final StringBuilder result = new StringBuilder();
        OkHttpClient client = new OkHttpClient();

        String json = String.format("{"
                + "\"model\": \"moonshot-v1-8k\", "
                + "\"messages\": [{\"role\": \"system\", \"content\": \"你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。\"}, "
                + "{\"role\": \"user\", \"content\": \"%s\"}], "
                + "\"temperature\": 0.3"
                + "}", input);
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        final Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + MOONSHOT_API_KEY)
                .build();

        final CountDownLatch latch = new CountDownLatch(1);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                result.append("请求失败: ").append(e.getMessage());
                latch.countDown();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    result.append(responseData);
                } else {
                    result.append("Error: ").append(response.code());
                }
                latch.countDown();
            }
        });

        try {
            latch.await(); // Wait for the async operation to complete.
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            result.append("线程被中断: ").append(e.getMessage());
        }

        return result.toString();
    }
}